package cn.xjt.screenShare.tcp;

import cn.xjt.screenShare.constant.EnumConstant;
import cn.xjt.screenShare.util.ImageUtil;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author xujiangtao
 * @version 1.0
 * @description Tcp服务端
 * @date 2022/8/17 21:21
 */
public class TcpClient {
    private ExecutorService executorServices=Executors.newCachedThreadPool();

    private static TcpClient tcpClient = new TcpClient();

    public static TcpClient getInstance(){
        return tcpClient;
    }

    @SneakyThrows
    public void start(String host, ImageView imageView){
        Socket socket = new Socket(host,EnumConstant.Port.SERVER.port);
        System.out.println("已连接服务器...");
        executorServices.submit(()->{
            InputStream inputStream = socket.getInputStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            while (true){
//                获取输入流接受文件
//                byte[] bytes = new byte[1048576*6];
//                int length = 0;
//                while ((length=inputStream.read(bytes))!=-1){
//                    os.write(bytes,0,length);
//                    if (inputStream.available()==0){
//                        break;
//                    }
//                }
//                byte[] byteArray = os.toByteArray();
//                ImageUtil.byte2image(byteArray, "/Users/xujiangtao/test/a.png");
//                os.reset();
                if (inputStream.available()!=0){
                    imageView.setImage(new Image(inputStream));
                }
            }
        });
    }

}
